<?php
  function insert_new_contact($data){
    return db_query("INSERT INTO {tvn_contact} (`full_name`,`phone`,`email`,`message`,`timespan`) VALUES (:full_name,:phone,:email,:message,:timespan)", array(':full_name'=>$data['full_name'],':phone'=>$data['phone'],':email'=>$data['email'],':message'=>$data['message'],':timespan'=>$data['timespan']));
  }

  function view_contact($id=0,$filter=''){
    $basestr="SELECT c.id,c.close,c.full_name, c.phone, c.email, c.message, c.timespan, c.close_time, f.name AS `first_read`, l.name AS `last_read`, cl.name AS `close_name` FROM {tvn_contact} c
    LEFT JOIN {users} f ON c.first_read = f.uid
    LEFT JOIN {users} l ON c.last_read = l.uid
    LEFT JOIN {users} cl ON c.close = cl.uid WHERE 1";

    $strquery = $basestr;
    if ($id!=0){
      $strquery = $strquery . ' AND c.id = '. $id;
    }
    if($filter == 'open'){
      $strquery = $strquery . ' AND c.close = 0';
    }
    if($filter == 'close'){
      $strquery = $strquery . ' AND c.close != 0';
    }
    $list = array();
    $result = db_query($strquery);
    while($data = $result->fetchObject()){
      $list[] = $data;
    }
    return $list;


  }

  function update_view_contact($data){
    global $user;

    $strquery="UPDATE {tvn_contact} SET last_read = ". $user->uid. " WHERE id=".$data->id;

    if(!$data->first_read){
      $strquery="UPDATE {tvn_contact} SET last_read = ". $user->uid. ",first_read = ".$user->uid." WHERE id=".$data->id;
    }
    return db_query($strquery);
  }

  function close_contact($id){
    global $user;
    return db_query("UPDATE {tvn_contact} SET close = ". $user->uid.", close_time= ". time()." WHERE id=".$id);
  }

  function delete_contact($id){
    return db_query("DELETE FROM {tvn_contact} WHERE id=".$id);
  }